package client

import (
	"context"
	"fmt"
	"gitee.com/enjoy_5/coupons-rpc/constant"
	pb "gitee.com/enjoy_5/coupons-rpc/proto/coupon"
	"gitee.com/xuxinzhi2206/corehub/nacos"
	"google.golang.org/grpc"
	"log"
)

func GetCouponClient(hand func(client pb.CouponsPbClient) error) error {
	service, err := nacos.FindService(constant.ServiceName, constant.GroupName)
	if err != nil {
		return fmt.Errorf("发现服务失败：%v", err)
	}
	// 连接到 gRPC 服务
	dial, err := grpc.Dial(service, grpc.WithInsecure())
	if err != nil {
		log.Printf("Failed to connect to server: %v", err)
	}
	defer dial.Close()

	couponsPbClient := pb.NewCouponsPbClient(dial)
	return hand(couponsPbClient)
}

func CouponInfoByID(in *pb.CouponInfoByIDReq) (resp *pb.CouponInfoByIDResp, err error) {
	return resp, GetCouponClient(func(client pb.CouponsPbClient) error {
		resp, err = client.CouponInfoByID(context.Background(), &pb.CouponInfoByIDReq{})
		if err != nil {
			return err
		}
		return nil
	})
}

func CouponListByUserID(in *pb.CouponListReq) (resp *pb.CouponListResp, err error) {
	return resp, GetCouponClient(func(client pb.CouponsPbClient) error {
		resp, err = client.CouponListByUserID(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

func CouponListUserByUserID(in *pb.CouponListUserReq) (resp *pb.CouponListUserResp, err error) {
	return resp, GetCouponClient(func(client pb.CouponsPbClient) error {
		resp, err = client.CouponListUserByUserID(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

func MemberList(in *pb.MemberListReq) (resp *pb.MemberListResp, err error) {
	return resp, GetCouponClient(func(client pb.CouponsPbClient) error {
		resp, err = client.MemberList(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

func CouponAdd(in *pb.CouponAddReq) (resp *pb.CouponAddResp, err error) {
	return resp, GetCouponClient(func(client pb.CouponsPbClient) error {
		resp, err = client.CouponAdd(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

func CouponBatchAdd(in *pb.CouponBatchAddReq) (resp *pb.CouponBatchAddResp, err error) {
	return resp, GetCouponClient(func(client pb.CouponsPbClient) error {
		resp, err = client.CouponBatchAdd(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

func PointsList(in *pb.PointsListReq) (resp *pb.PointsListResp, err error) {
	return resp, GetCouponClient(func(client pb.CouponsPbClient) error {
		resp, err = client.PointsList(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}

func PointsInfo(in *pb.PointsInfoReq) (resp *pb.PointsInfoResp, err error) {
	return resp, GetCouponClient(func(client pb.CouponsPbClient) error {
		resp, err = client.PointsInfo(context.Background(), in)
		if err != nil {
			return err
		}
		return nil
	})
}
